/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedFaceData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useState, useMemo, useEffect } from 'react';

type Params = {
  mode: string;
  curve: string;
  point: string;
  length?: number;
  topoint?: string;
  toplane?: string;
};

type FormData = {
  mode: string;
  curve: pickedLineData;
  point: pickedVertexData;
  length?: number;
  topoint?: pickedVertexData;
  toplane?: pickedFaceData;
};

function CommandExtendCurve({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormData = {
    mode: 'ByLength',
    curve: null,
    point: null,
    length: 60,
    topoint: null,
    toplane: null,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const { mode, curve, point, length, topoint, toplane } = formData;

    const params: Params = {
      mode: mode,
      curve: curve?.edgeId,
      point: point?.vertexId,
      length: length,
      topoint: topoint?.vertexId,
      toplane: toplane?.meshId,
    };

    return confirmCommand({ type: 'Extend', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { mode, curve, point, length, topoint, toplane } = params;

    await initEditDependency([curve, point, topoint, toplane]);

    setFormData({
      mode: mode,
      curve: curve
        ? (picker.generatePickObjByPickID(curve) as pickedLineData)
        : null,
      point: point
        ? (picker.generatePickObjByPickID(point) as pickedVertexData)
        : null,
      length: length,
      topoint: topoint
        ? (picker.generatePickObjByPickID(topoint) as pickedVertexData)
        : null,
      toplane: toplane
        ? (picker.generatePickObjByPickID(toplane) as pickedFaceData)
        : null,
    });
  }, []);

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-display-draft-sweep-curve', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { mode, curve, point, length, topoint, toplane } = formData;

    if (mode === 'ByLength') {
      return curve != null && point != null && (length != null || length > 0);
    }

    if (mode === 'ToPoint' || mode === 'DynamicToPoint') {
      return curve != null && point != null && topoint != null;
    }

    return curve != null && point != null && toplane != null;
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        length:
          formData.mode === 'ByLength'
            ? {
                type: 'number',
                title: '长度',
                format: NumberInputFormat.Length,
              }
            : null,
        topoint:
          formData.mode === 'ToPoint' || formData.mode === 'DynamicToPoint'
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickVertex,
              }
            : null,
        toplane:
          formData.mode === 'ToPlane' ||
          formData.mode === 'PerpendicularToPlane'
            ? {
                type: 'string',
                format: PickInputRJSFFormat.PickSurface,
              }
            : null,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties: {
        mode: {
          title: '模式',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '按长度延伸',
              const: 'ByLength',
            },
            {
              type: 'string',
              title: '延伸到点',
              const: 'ToPoint',
            },
            {
              type: 'string',
              title: '动态延伸到点',
              const: 'DynamicToPoint',
            },
            {
              type: 'string',
              title: '延伸到面',
              const: 'ToPlane',
            },
            {
              type: 'string',
              title: '垂直于平面延伸',
              const: 'PerpendicularToPlane',
            },
          ],
          default: 'ByLength',
        },
        curve: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        point: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertex,
        },
        ...properties,
      },
    } as RJSFSchema;
  }, [formData.mode]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
        },
        point: {
          'ui:placeholder': '请输入曲线上的点',
        },
        length: {
          'ui:placeholder': '请输入长度',
        },
        topoint: {
          'ui:placeholder': '请输入到达点',
        },
        toplane: {
          'ui:placeholder': '请输入到达面',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
      }}
      submitText='完成'
      isFormDataValid={isFormDataValid()}
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdExtendCurve: CurvedBaseCommand = {
  id: 'CmdExtendCurve',
  label: 'command.extend-curve',
  icon: 'commands/curved/extend-curve',
  create: (label, onClose, props) => (
    <CommandExtendCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
